import wizard
import pooler
from tools.misc import UpdateableStr,UpdateableDict
import time
import operator
from osv import osv, fields
from osv.orm import intersect
import tools.sql
from tools import config
from tools.translate import _
from mx import DateTime
import netsvc

FORM = UpdateableStr()

Fields=UpdateableDict()
Forms=UpdateableStr()
confirm_form=UpdateableStr()
Form_error=UpdateableStr()
Form_error.string='''<form string='Error'>
<label>You must input Job Code and Job Name</label>
</form>'''
confirm_form.string='''<form string="Warning">
    <separator string="Are you sure insert new Sub Job?"/>
    <!--<field name='owner1' invisible="1"/>-->
</form>'''
#confirm_fields={'owner1': {'string': 'Owner', 'type': 'many2one', 'relation': 'res.partner'}}

def _check(self, cr, uid, data, context):
    pool = pooler.get_pool(cr.dbname)
    sale_obj = pool.get('sale.order')
    sale=sale_obj.browse(cr,uid,data['id'],context=context)
    
    project_e = sale.project_e_id
    project_m = sale.project_m_id
    #raise osv.except_osv("Error",line_check)
     
    line_check=True #Tam thoi
    finish=False
    if (project_e and project_m) or (sale.quotation_type=='E' and project_e) or (sale.quotation_type=='M' and project_m):
        finish=True
    if finish:
        return 'end'
    else:
        return 'create_project'

   
def _input_main(self, cr, uid, data, context):
    pool = pooler.get_pool(cr.dbname)
    sale_obj = pool.get('sale.order')

    sale=sale_obj.browse(cr,uid,data['id'],context=context)
    #prj_name=sale_obj.read(cr,uid,data['id'],['project_name'])['project_name']
    prj_name = sale.project_name
    owner=sale.owner_id.id
    client_id=sale.partner_id.id
    if sale.project_e_id:
        project_e = 1
    else:
        project_e = 0
    
    if sale.project_m_id:
        project_m = 1
    else:
        project_m = 0
    
    typeaction=''

    #New code Electrical Project
    cr.execute("Select * from vwnew_electrical_project_code order by newcode asc")
    list_newcode=''
    for ncode,nname in cr.fetchall(): 
        if list_newcode=='':
            list_newcode="('"+ncode+"','"+ncode+": "+nname+"')"
        else:
            list_newcode=list_newcode+",('"+ncode+"','"+ncode+": "+nname+"')"
    list_newcode="["+list_newcode+"]"
    
    #New code Mechanical Project
    cr.execute("Select * from vwnew_mechanical_project_code order by newcode asc")
    list_newcode_mechanical=''
#    lb=''
    for ncode,nname in cr.fetchall():
        if list_newcode_mechanical=='':
            list_newcode_mechanical="('"+ncode+"','"+ncode+": "+nname+"')"
        else:
            list_newcode_mechanical=list_newcode_mechanical+",('"+ncode+"','"+ncode+": "+nname+"')"
    list_newcode_mechanical="["+list_newcode_mechanical+"]"
    
    #Existing code
    cr.execute("Select code,name,project_type from kdvn_project where project_status='doing' and to_char(registration_date,'YY')=to_char(now(),'YY')")
    list_exist_electrical=''
    list_exist_mechanical=''
    list_exist_electrical1=''
    list_exist_mechanical1=''
    for ncode,nname,type in cr.fetchall():
        nname = nname.replace("'","`")
        if type=='E':         
            if list_exist_electrical=='':
                list_exist_electrical="('"+ncode+"','"+ncode+": "+nname+"')"
                
                list_exist_electrical1='("'+ncode+'","'+ncode+': '+nname+'")'
            else:
                list_exist_electrical=list_exist_electrical+",('"+ncode+"','"+ncode+": "+nname+"')"
                
                list_exist_electrical1=list_exist_electrical1+',("'+ncode+'","'+ncode+": "+nname+'")'
                
        elif type=='M':
            if list_exist_mechanical=='':
                list_exist_mechanical="('"+ncode+"','"+ncode+": "+nname+"')"
                
                list_exist_mechanical1='("'+ncode+'","'+ncode+': '+nname+'")'
            else:
                list_exist_mechanical=list_exist_mechanical+",('"+ncode+"','"+ncode+": "+nname+"')"
                
                list_exist_mechanical1=list_exist_mechanical1+',("'+ncode+'","'+ncode+": "+nname+'")'
                
    list_exist_electrical="["+list_exist_electrical+"]"
    list_exist_mechanical="["+list_exist_mechanical+"]"
    
    list_exist_electrical1="["+list_exist_electrical1+"]"
    list_exist_mechanical1="["+list_exist_mechanical1+"]"
    
    Fields['client_id']={'string':'Client','type':'many2one','relation':"res.partner",'readonly':True,'default': lambda *a:client_id}
    Fields['owner_id']={'string':'Owner','type':'many2one','relation':"res.partner",'readonly':True,'default': lambda *a:owner}
    Fields['job_code']={'string':'New Code','type':'selection','selection':eval(list_newcode)}
    Fields['job_code_other']={'string':'Job Code','type':'char','size':128}
    Fields['job_name']={'string':'Job Name','type':'char','size':256}#,'default': lambda *a:prj_name}
    
    Fields['job_m_code']={'string':'New Code','type':'selection','selection':eval(list_newcode_mechanical)}
    Fields['job_m_code_other']={'string':'Job Code','type':'char','size':128,}
    Fields['job_m_name']={'string':'Job Name','type':'char','size':256}#,'default': lambda *a:prj_name}
    try:
        Fields['job_e_code_exist']={'string':'Code Exist E.','type':'selection','selection':eval(list_exist_electrical)}
        Fields['job_m_code_exist']={'string':'Code Exist M.','type':'selection','selection':eval(list_exist_mechanical)}
    except:
        Fields['job_e_code_exist']={'string':'Code Exist E.','type':'selection','selection':eval(list_exist_electrical1)}
        Fields['job_m_code_exist']={'string':'Code Exist M.','type':'selection','selection':eval(list_exist_mechanical1)}

    Forms.string='''<?xml version="1.0"?>
                    <form string="Create New Project">
                        <!--<label colspan="4">Suggest:+ lb +</label>-->
                        <separator string="Customer Infomation"/>
                        <field name="owner_id"/>
                        <field name="client_id"/>
                        <group colspan="2" invisible="'''+str(project_e)+'''">
                            <separator string="Electrical"/>
                            <field name="job_e_code_exist" string="Exist E. Code This Year" colspan="4" on_change="_onchange_e_exist()"/>
                            <field name="job_code" on_change="_onchange(job_code)" string="Suggest P.E. New Code" colspan="4"/>
                            <newline/>
                            <field name="job_code_other" string="Project E. New Code" colspan="4" attrs="{'required':[('job_name','!=','')]}"/>
                            <field name="job_name" string="Project E. Name" colspan="4" attrs="{'required':[('job_code_other','!=','')]}"/>
                        </group>
                        <group colspan="2" invisible="'''+str(project_m)+'''">
                            <separator string="Mechanical" colspan="2"/>
                            <field name="job_m_code_exist" string="Exist M. Code This Year" colspan="4" on_change="_onchange_m_exist()"/>
                            <field name="job_m_code" on_change="_onchange_me(job_m_code)" string="Suggest P.M. New Code" colspan="4"/>
                            <field name="job_m_code_other" attrs="{'required':[('job_m_name','!=','')]}" string="Project M. New Code" colspan="4" />
                            <field name="job_m_name" string="Project M. Name" colspan="4" attrs="{'required':[('job_m_code_other','!=','')]}"/>
                        </group>
                    </form>'''
    return {}


def _finish_(self, cr, uid, data, context):
    #Comment out when separate work received button
#    pool = pooler.get_pool(cr.dbname)
#    sale_obj = pool.get('sale.order')
#    #wf_service = netsvc.LocalService("workflow")
#    #wf_service.trg_validate(uid, 'sale.order', data['id'], 'order_confirm', cr)
#    sale_obj.write(cr,uid,data['id'],{'state':'done'})
    return {}

def _update_(self, cr, uid, data, context):
    pool = pooler.get_pool(cr.dbname)
    sale_obj = pool.get('sale.order')
    kdvn_project_obj = pool.get('kdvn.project')    


#Thieu contract
    #Mechanical & Electrical
    if data['form']:
        prj_e_id = False
        prj_m_id = False
        
        quotation_check_list_a = False
        
        if data['form']['job_code_other']:
            cr.execute("Select \
                               name,\
                               site_manager_e_id,\
                               site_manager_m_id,\
                               project_manager_id,\
                               project_manager_m_id,\
                               owner_id,partner_id,\
                               partner_order_id,partner_invoice_id,\
                               currency_id\
                        from sale_order where id=%s" % data['id'])
            quotation_check_list_a = cr.dictfetchone()
            
            site_manager_e_id = False
            project_manager_e_id = False
            site_manager_m_id = False
            project_manager_m_id = False
            
            prj_name = False
            prj_owner_id = False
            prj_partner_id = False
            prj_partner_order_id = False
            prj_partner_invoice_id = False
            curr_id = False

            if quotation_check_list_a:
                site_manager_e_id = quotation_check_list_a['site_manager_e_id'] 
                project_manager_e_id = quotation_check_list_a['project_manager_id']
                
                site_manager_m_id = quotation_check_list_a['site_manager_m_id'] 
                project_manager_m_id = quotation_check_list_a['project_manager_m_id']
                    
                curr_id = quotation_check_list_a['currency_id']
                
                prj_name = quotation_check_list_a['name']

                prj_owner_id = quotation_check_list_a['owner_id']
                prj_client_id = quotation_check_list_a['partner_id']
                prj_partner_order_id = quotation_check_list_a['partner_order_id']
                prj_partner_invoice_id = quotation_check_list_a['partner_invoice_id']
                            
            prj_e_code=data['form']['job_code_other']
            prj_e_name=data['form']['job_name']
            new_e_vals={"code":prj_e_code,"name":prj_e_name,
                        'owner_id':prj_owner_id,'client_id':prj_client_id,
                        'project_manager_id':project_manager_e_id,'site_manager_id':site_manager_e_id,
                        'address_id':prj_partner_order_id,'invoice_address_id':prj_partner_invoice_id}
            
            prj_e_id=kdvn_project_obj.create(cr,uid,new_e_vals,{'currency_id':curr_id})
            
        elif data['form']['job_e_code_exist']:
            prj_e_exist_code=data['form']['job_e_code_exist']
            prj_e_id=kdvn_project_obj.search(cr,uid,[('code','=',prj_e_exist_code)])[0]

#Comment Out Separate Work Received Button            
#        if prj_e_id:
#            sale_obj.write(cr,uid,data['id'],{'state':'done'})


#            wf_service = netsvc.LocalService("workflow")
#            wf_service.trg_validate(uid, 'sale.order', data['id'], 'order_confirm', cr)

        if data['form']['job_m_code_other']:
            
            if not quotation_check_list_a:
                cr.execute("Select \
                               name,\
                               site_manager_e_id,\
                               site_manager_m_id,\
                               project_manager_id,\
                               project_manager_m_id,\
                               owner_id,partner_id,\
                               partner_order_id,partner_invoice_id,\
                               currency_id\
                        from sale_order where id=%s" % data['id'])
                quotation_check_list_a = cr.dictfetchone()
                
                prj_name = False
                
                prj_owner_id = False
                prj_partner_id = False
                prj_partner_order_id = False
                prj_partner_invoice_id = False
                curr_id = False
                
                if quotation_check_list_a:
                    site_manager_m_id = quotation_check_list_a['project_manager_m_id'] 
                    project_manager_m_id = quotation_check_list_a['site_manager_m_id']
                    prj_name = quotation_check_list_a['name']
                    
                    prj_owner_id = quotation_check_list_a['owner_id']
                    prj_client_id = quotation_check_list_a['partner_id']
                    prj_partner_order_id = quotation_check_list_a['partner_order_id']
                    prj_partner_invoice_id = quotation_check_list_a['partner_invoice_id']
            
            
            #Create New Mechanical Project                
            prj_m_code=data['form']['job_m_code_other']
            prj_m_name=data['form']['job_m_name']
            new_m_vals={"code":prj_m_code,"name":prj_m_name,'project_type':'M',
                        'owner_id':prj_owner_id,'client_id':prj_client_id,
                        'project_manager_id':project_manager_m_id,'site_manager_id':site_manager_m_id,
                        'address_id':prj_partner_order_id,'invoice_address_id':prj_partner_invoice_id}
            prj_m_id=kdvn_project_obj.create(cr,uid,new_m_vals,{'currency_id':curr_id})

        elif data['form']['job_m_code_exist']:
            prj_m_exist_code=data['form']['job_m_code_exist']
            prj_m_id=kdvn_project_obj.search(cr,uid,[('code','=',prj_m_exist_code)])[0]
        if prj_m_id and prj_e_id:
            #wf_service = netsvc.LocalService("workflow")
            #wf_service.trg_validate(uid, 'sale.order', data['id'], 'order_confirm', cr)
            sale_obj.write(cr,uid,data['id'],{'project_m_id':prj_m_id,'project_e_id':prj_e_id}) # Comment Out Separate Work Received Button ,'state':'done'
        elif prj_m_id:
#            wf_service = netsvc.LocalService("workflow")
#            wf_service.trg_validate(uid, 'sale.order', data['id'], 'order_confirm', cr) 
            sale_obj.write(cr,uid,data['id'],{'project_m_id':prj_m_id}) # Comment Out Separate Work Received Button ,'state':'done' 
        elif prj_e_id:
            #wf_service = netsvc.LocalService("workflow")
            #wf_service.trg_validate(uid, 'sale.order', data['id'], 'order_confirm', cr)
            sale_obj.write(cr,uid,data['id'],{'project_e_id':prj_e_id})  # Comment Out Separate Work Received Button ,'state':'done' 
    return {}

class quotation_to_job(osv.osv_memory): #Using onchange only
    _name='wizard.quotation_to_job'
    _auto=False
    
    def _onchange_e_exist(self, cr, uid, ids,pinput=False):
        return {'value':{'job_code_other':False,'job_name':False}}
    
    def _onchange_m_exist(self, cr, uid, ids,pinput=False):
        return {'value':{'job_m_code_other':False,'job_m_name':False}}
        
    def _onchange(self, cr, uid, ids, pinput=False):
        return {'value':{'job_code_other':pinput,'job_e_code_exist':False}}
    
    def _onchange_me(self, cr, uid, ids, pinput=False):
        return {'value':{'job_m_code_other':pinput,'job_m_code_exist':False}}
    
#    def _onchange_code_subjob(self, cr, uid, ids, pinput=False):
#        pool = pooler.get_pool(cr.dbname)
#        prj_obj = pool.get('account.analytic.account')
#        try:
#            pinput=int(pinput)
#            pinput=False
#        except:
#            pinput=pinput
#        return {'value':{'new_job':pinput}}    
quotation_to_job()

class QuotationJob(wizard.interface):
    """
    Quotation and Job
    """    
    
    def _open_project(self, cr, uid, data, context):
        pool_obj = pooler.get_pool(cr.dbname)
        sale_obj = pool_obj.get('sale.order')
        sale=sale_obj.browse(cr,uid,data['id'],context=context)
        job=sale.project_id.id
        #raise osv.except_osv("Error","%s" % data)
        return {
            'domain': "[('id','=',"+str(job)+")]",
            'name': 'Projects',
            'view_type': 'form',
            'view_mode': 'form,tree',
            'res_model': 'account.analytic.account',
            'res_id':job,
            'view_id':False,
            'target':'new',
            #'views': [(False,'tree'),(False,'form'),],
            'type': 'ir.actions.act_window',
        }

    states = {
        'init': {
            'actions': [],
            'result': {'type': 'choice','next_state':_check}},
                               
        'create_project': {
            'actions': [_input_main],
            'result': {'type': 'form','arch': Forms,'fields':Fields,'state': [
                    ('finish', '_Ok', 'gtk-ok', True),
                    ('end', '_Cancel','gtk-cancel'),
                    ]
                      }},
        'finish': {
            'actions': [_update_],
            'result': {
                'type': 'state',
#                'action':_open_project,
                'state': 'end'
            }},
        'end': {
            'actions': [_finish_],
            'result': {
                'type': 'state',
#                'action':_open_project,
                'state': 'end'
            }},
    }
QuotationJob('quotation_to_job')
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
